#include "Image.h"
#include <cstdio>
#include <ctype.h>
/*static*/ void Image::Loader::SkipPGMComments(FILE *pFile)
{
	char c;
	while(1) {
		while(isspace(c = fgetc(pFile)));
		if (c == '#') GoToNextLine(pFile);
		else break;
	}
	fseek(pFile, -1, SEEK_CUR);
}

/*static*/ void Image::Loader::GoToNextLine(FILE *pFile)
{
	int c;
	while((c = fgetc(pFile)) != '\n' && c != EOF);
}

/*static*/ Image *Image::Loader::Load(const char *szFilename)
{
	Image *img;
	FILE *f;
	S32 tmp;
	U8 *p;
	S32 nWidth, nHeight;
	
	f = fopen(szFilename,"rb");
	if (f == NULL)
	{
		return NULL; 	
	}
	SkipPGMComments(f);
	if (fgetc(f) != 'P' || fgetc(f) != '5')
	{
		delete (img);
		fclose(f);
		puts("bad signature"); 
		return NULL;
	}
	SkipPGMComments(f);	
	if (fscanf(f,"%d",&nWidth) < 1)
	{
		delete(img);
		fclose(f);
		puts("no width"); return NULL;
	}
	SkipPGMComments(f);	
	if (fscanf(f,"%d",&nHeight) < 1)
	{
		delete(img);
		fclose(f);
		puts("no height"); return NULL;
	}	
	img = new Image(nWidth, nHeight);
	if (img == NULL) 
	{
		puts("Not enough memory"); 
		return NULL;
	}
	SkipPGMComments(f);
	if  (fscanf(f,"%d",&tmp) < 1)
	{
		delete(img);
		fclose(f);
		puts("no threshold"); return NULL;
	}
	GoToNextLine(f);
	if (tmp != 255)
	{
		delete(img);
		fclose(f);
		puts("weird threshold"); return NULL;	
	}
	tmp = nWidth * nHeight;
	p = img->m_pData;
	while(tmp)
	{
		*p = fgetc(f);
		p++;
		tmp--;
	}
	
	fclose(f);
	return img;	
}

